package cz.zcu.fav.rat.rest.utils;

import org.hibernate.service.spi.ServiceException;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cz.zcu.fav.rat.rest.errorhandling.UnknownResourceException;

public class RestUtils
{

	private static DateTimeFormatter formatter = DateTimeFormat
			.forPattern("yyyy-MM-dd-HH-mm");
	private static Logger logger = LoggerFactory.getLogger(RestUtils.class);

	public static LocalDateTime convertRestTimeToJodaTime(String time)
			throws ServiceException
	{
		if (org.apache.commons.lang3.StringUtils.isEmpty(time))
		{
			throw new UnknownResourceException("Time is empty");
		}

		try
		{
			return formatter.parseDateTime(time).toLocalDateTime();
		} catch (IllegalArgumentException ex)
		{
			logger.debug("String " + time
					+ " cannot be parsed to internal date format", ex);
			throw new UnknownResourceException("String " + time
					+ " cannot be parsed to internal date format");
		}

	}

	public static String convertJodaTimeToRestTime(LocalDateTime time)
			throws ServiceException
	{
		return time.toString(formatter);
	}

}
